package zjut.raymond.witdemo.util;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.util.Log;

import com.alibaba.fastjson.JSON;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import zjut.raymond.witdemo.algorithm.OnLocationChangedCallback;

public class LocationWifiScanUtils extends WifiScanUtils {
    private OnLocationChangedCallback changedCallback;

    public void setChangedCallback(OnLocationChangedCallback changedCallback) {
        this.changedCallback = changedCallback;
    }

    int n = 10;

    public LocationWifiScanUtils(Context context) {
        super(context);
    }

    @Override
    public void processScanResult(List<ScanResult> results) {
        List<ScanResult> subList = results.subList(0, n);
        Map<String, Object> map = new HashMap<>();
        for (ScanResult result : subList) {
            map.put(result.BSSID, result.level);
        }
        String json = JSON.toJSONString(map);

        RequestParams requestParams = new RequestParams();
        requestParams.addFormDataPart("fingerprint", json);
        executorService.execute(() -> HttpRequest.post("http://47.101.186.100:9102/location/wifilocation", requestParams, new BaseHttpRequestCallback<ApiResult>(){
            @Override
            protected void onSuccess(ApiResult apiResult) {
                if (apiResult.getCode() == 200) {
                    Map<String, Object> map = (Map<String, Object>) apiResult.getData();
                    BigDecimal x = (BigDecimal) map.get("x");
                    BigDecimal y = (BigDecimal) map.get("y");
                    changedCallback.onLocationChanged(x.doubleValue(), y.doubleValue());
                    Log.d(TAG, "onResponse: 定位结果" + x + "," + y);
                }
            }
        }));
    }
}
